<template>
  <div class="app-container">
    <!-- 页面标题和时间筛选 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <h2 class="page-title">商品数据分析</h2>
        <p class="page-subtitle">基于趋势-结构-矩阵三维度的可视化决策支持</p>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
          class="mr10"
        />
        <el-button type="primary" icon="el-icon-refresh" @click="refreshData">刷新数据</el-button>
      </el-col>
    </el-row>

    <!-- 综合统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-goods" style="color: #409EFF;"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ summaryData.total_products || 0 }}</div>
            <div class="stat-label">商品总数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-collection-tag" style="color: #67C23A;"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ summaryData.total_skus || 0 }}</div>
            <div class="stat-label">SKU总数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-money" style="color: #E6A23C;"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(summaryData.total_sales_amount) || 0 }}</div>
            <div class="stat-label">总销售额</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon">
            <i class="el-icon-pie-chart" style="color: #F56C6C;"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatPercent(summaryData.avg_margin_rate) }}%</div>
            <div class="stat-label">平均毛利率</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <!-- 趋势维度：折线图 -->
      <el-col :span="24" class="mb20">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">
              <i class="el-icon-trend-charts"></i>
              趋势维度：销量动态监测
            </span>
            <div class="chart-controls">
              <el-radio-group v-model="trendTimeType" size="small" @change="loadTrendData">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div ref="trendChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!-- 结构维度：环形饼图 -->
      <el-col :span="12" class="mb20">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">
              <i class="el-icon-pie-chart"></i>
              结构维度：品类分析
            </span>
          </div>
          <div ref="categoryChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 矩阵维度：气泡图 -->
      <el-col :span="12" class="mb20">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">
              <i class="el-icon-data-analysis"></i>
              矩阵维度：SKU评估
            </span>
            <div class="chart-controls">
              <el-tooltip content="仅对矩阵图表启用异常数据过滤，自动剔除偏离中心的错误数据点" placement="top">
                <el-switch
                  v-model="outlierFilter.enabled"
                  active-text="过滤异常"
                  inactive-text="显示全部"
                  @change="onFilterChange"
                  size="small">
                </el-switch>
              </el-tooltip>
            </div>
          </div>
          <div ref="matrixChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- SKU详情表格 -->
    <el-row :gutter="20" class="mt20">
      <el-col :span="24">
        <el-card>
          <div slot="header" class="chart-header">
            <span class="chart-title">
              <i class="el-icon-document"></i>
              SKU详细数据
            </span>
            <div class="chart-controls">
              <el-form :inline="true" size="small">
                <el-form-item label="SKU筛选:">
                  <id-selector
                    v-model="selectedSkuIds"
                    placeholder="请选择SKU"
                    dialog-title="选择SKU"
                    :api-function="listSku"
                    :get-api-function="getSku"
                    id-field="skuId"
                    name-field="skuName"
                    id-label="SKU ID"
                    name-label="SKU名称"
                    search-label="SKU名称"
                    search-placeholder="请输入SKU名称"
                    :extra-columns="[{prop: 'skuCode', label: 'SKU编码'}, {prop: 'price', label: '价格'}]"
                    :multiple="true"
                    @input="handleSkuFilter"
                    style="width: 300px;"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="applySkuFilter">筛选</el-button>
                  <el-button icon="el-icon-refresh" @click="clearSkuFilter">清除</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-table :data="matrixData" style="width: 100%" v-loading="loading">
             <el-table-column prop="name" label="SKU名称" width="200" show-overflow-tooltip />
             <el-table-column prop="product_name" label="商品名称" width="180" show-overflow-tooltip />
             <el-table-column prop="category" label="品类" width="120" />
             <el-table-column prop="cost_price" label="成本价" width="120" align="right">
               <template slot-scope="scope">
                 ¥{{ formatNumber(scope.row.cost_price) }}
               </template>
             </el-table-column>
             <el-table-column prop="selling_price" label="销售价" width="120" align="right">
               <template slot-scope="scope">
                 ¥{{ formatNumber(scope.row.selling_price) }}
               </template>
             </el-table-column>
             <el-table-column prop="sales_quantity" label="销售数量" width="100" align="right" />
             <el-table-column prop="marginRate" label="毛利率" width="100" align="right">
               <template slot-scope="scope">
                 {{ formatPercent(scope.row.marginRate) }}%
               </template>
             </el-table-column>
             <el-table-column prop="turnoverRate" label="周转率" width="100" align="right">
               <template slot-scope="scope">
                 {{ formatPercent(scope.row.turnoverRate) }}%
               </template>
             </el-table-column>
             <el-table-column prop="quadrant" label="象限分类" width="120">
               <template slot-scope="scope">
                 <el-tag :type="getQuadrantType(scope.row.quadrant)">
                   {{ scope.row.quadrant }}
                 </el-tag>
               </template>
             </el-table-column>
             <el-table-column prop="stock_quantity" label="库存数量" width="100" align="right" />
             <el-table-column prop="unit_price" label="单价" width="100" align="right">
               <template slot-scope="scope">
                 ¥{{ formatNumber(scope.row.unit_price) }}
               </template>
             </el-table-column>
           </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getSalesTrend, getCategoryStructure, getSkuMatrix, getSummaryData } from '@/api/statistics/goodAnalyse'
import { listSku, getSku } from '@/api/fun/sku'
import IdSelector from '@/components/IdSelector'

export default {
  name: 'GoodAnalyseCore',
  components: {
    IdSelector
  },
  data() {
    return {
      loading: false,
      dateRange: [],
      trendTimeType: 'day',
      summaryData: {},
      trendData: [],
      categoryData: [],
      matrixData: [],
      filteredMatrixData: [], // 过滤后的矩阵数据
      originalMatrixData: [], // 原始矩阵数据，用于SKU筛选
      selectedSkuIds: [], // 选中的SKU ID列表
      trendChart: null,
      categoryChart: null,
      matrixChart: null,
      // 异常数据过滤配置
      outlierFilter: {
        enabled: true, // 是否启用异常值过滤
        method: 'iqr', // 过滤方法：iqr（四分位距）或 zscore（标准分数）
        sensitivity: 1.5, // 敏感度系数，越小过滤越严格
        dimensions: ['turnoverRate', 'marginRate', 'sales_amount'] // 检测维度
      }
    }
  },
  mounted() {
    this.initDateRange()
    this.initCharts()
    this.loadAllData()
  },
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
    if (this.categoryChart) {
      this.categoryChart.dispose()
    }
    if (this.matrixChart) {
      this.matrixChart.dispose()
    }
  },
  methods: {
    // 初始化日期范围（默认最近30天）
    initDateRange() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 30 * 24 * 60 * 60 * 1000)
      this.dateRange = [this.formatDate(start), this.formatDate(end)]
    },

    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.trendChart = echarts.init(this.$refs.trendChart)
        this.categoryChart = echarts.init(this.$refs.categoryChart)
        this.matrixChart = echarts.init(this.$refs.matrixChart)

        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize)
      })
    },

    // 加载所有数据
    async loadAllData() {
      this.loading = true
      try {
        // 先加载矩阵数据，再加载统计数据（因为统计数据可能需要依赖矩阵数据）
        await this.loadMatrixData()
        await Promise.all([
          this.loadSummaryData(),
          this.loadTrendData(),
          this.loadCategoryData()
        ])
      } catch (error) {
        this.$modal.msgError('数据加载失败：' + error.message)
      } finally {
        this.loading = false
      }
    },

    // 加载综合统计数据
    async loadSummaryData() {
      const params = this.getDateParams()
      const response = await getSummaryData(params)
      this.summaryData = response.data || {}
      
      // 如果后端没有返回total_sales_amount，从matrixData计算
      if (!this.summaryData.total_sales_amount && this.matrixData.length > 0) {
        this.summaryData.total_sales_amount = this.matrixData.reduce((sum, item) => {
          return sum + (parseFloat(item.sales_amount) || 0)
        }, 0)
      }
    },

    // 加载趋势数据
    async loadTrendData() {
      const params = {
        ...this.getDateParams(),
        timeType: this.trendTimeType
      }
      const response = await getSalesTrend(params)
      this.trendData = response.data || []
      this.renderTrendChart()
    },

    // 加载品类数据
    async loadCategoryData() {
      const params = this.getDateParams()
      const response = await getCategoryStructure(params)
      this.categoryData = response.data || []
      this.renderCategoryChart()
    },

    // 加载矩阵数据
    async loadMatrixData() {
      const params = this.getDateParams()
      const response = await getSkuMatrix(params)
      this.originalMatrixData = response.data || []
      this.applySkuFilterToData()
      this.filterOutliers()
      this.renderMatrixChart()
    },

    // 异常数据检测和过滤
    filterOutliers() {
      if (!this.outlierFilter.enabled || !this.matrixData.length) {
        this.filteredMatrixData = [...this.matrixData]
        return
      }

      const filtered = []
      
      // 为每个维度计算统计值
      const stats = {}
      this.outlierFilter.dimensions.forEach(dim => {
        const values = this.matrixData
          .map(item => parseFloat(item[dim]) || 0)
          .filter(val => !isNaN(val) && isFinite(val))
          .sort((a, b) => a - b)
        
        if (values.length === 0) return
        
        if (this.outlierFilter.method === 'iqr') {
          // 四分位距方法
          const q1Index = Math.floor(values.length * 0.25)
          const q3Index = Math.floor(values.length * 0.75)
          const q1 = values[q1Index]
          const q3 = values[q3Index]
          const iqr = q3 - q1
          const multiplier = this.outlierFilter.sensitivity
          
          stats[dim] = {
            lower: q1 - multiplier * iqr,
            upper: q3 + multiplier * iqr
          }
        } else if (this.outlierFilter.method === 'zscore') {
          // 标准分数方法
          const mean = values.reduce((sum, val) => sum + val, 0) / values.length
          const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length
          const stdDev = Math.sqrt(variance)
          const threshold = this.outlierFilter.sensitivity * 2 // 通常使用2倍标准差
          
          stats[dim] = {
            lower: mean - threshold * stdDev,
            upper: mean + threshold * stdDev
          }
        }
      })

      // 过滤数据
      this.matrixData.forEach(item => {
        let isOutlier = false
        
        for (const dim of this.outlierFilter.dimensions) {
          const value = parseFloat(item[dim]) || 0
          const stat = stats[dim]
          
          if (stat && (value < stat.lower || value > stat.upper)) {
            isOutlier = true
            break
          }
        }
        
        if (!isOutlier) {
          filtered.push(item)
        }
      })

      this.filteredMatrixData = filtered
      
      // 输出过滤信息到控制台
      const removedCount = this.matrixData.length - filtered.length
      if (removedCount > 0) {
        console.log(`异常数据过滤：移除了 ${removedCount} 个异常数据点，保留 ${filtered.length} 个正常数据点`)
      }
    },

    // 渲染趋势图表
    renderTrendChart() {
      if (!this.trendChart) return

      const option = {
        title: {
          text: '销量趋势分析',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: ['销量', '销售额'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.trendData.map(item => item.date_label)
        },
        yAxis: [
          {
            type: 'value',
            name: '销量',
            position: 'left'
          },
          {
            type: 'value',
            name: '销售额',
            position: 'right'
          }
        ],
        series: [
          {
            name: '销量',
            type: 'line',
            data: this.trendData.map(item => item.sales_quantity),
            smooth: true,
            itemStyle: { color: '#409EFF' }
          },
          {
            name: '销售额',
            type: 'line',
            yAxisIndex: 1,
            data: this.trendData.map(item => item.sales_amount),
            smooth: true,
            itemStyle: { color: '#67C23A' }
          }
        ]
      }

      this.trendChart.setOption(option)
    },

    // 渲染品类图表
    renderCategoryChart() {
      if (!this.categoryChart) return

      const option = {
        title: {
          text: '品类销售占比',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '销售额',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: this.categoryData.map(item => ({
              name: item.name,
              value: item.value
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}\n{d}%'
            }
          }
        ]
      }

      this.categoryChart.setOption(option)
    },

    // 渲染矩阵图表
    renderMatrixChart() {
      if (!this.matrixChart) return

      // 计算数据的中位数作为分割线
      const turnoverRates = this.filteredMatrixData.map(item => parseFloat(item.turnoverRate) || 0)
      const marginRates = this.filteredMatrixData.map(item => parseFloat(item.marginRate) || 0)
      
      const turnoverMedian = this.calculateMedian(turnoverRates)
      const marginMedian = this.calculateMedian(marginRates)

      const option = {
        title: {
          text: 'SKU性能矩阵',
          left: 'center',
          textStyle: { fontSize: 16 }
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const data = params.data
            const quadrantDesc = this.getQuadrantDescription(data.quadrant)
            return `<div style="text-align: left;">
                      <strong>${data.name}</strong><br/>
                      <span style="color: #666;">━━━━━━━━━━━━━━━━</span><br/>
                      📊 周转率: <strong>${data.value[0].toFixed(2)}%</strong><br/>
                      💰 毛利率: <strong>${data.value[1].toFixed(2)}%</strong><br/>
                      💵 销售额: <strong>¥${this.formatNumber(data.value[2])}</strong><br/>
                      <span style="color: #666;">━━━━━━━━━━━━━━━━</span><br/>
                      🎯 象限: <span style="color: ${this.getQuadrantColor(data.quadrant)}; font-weight: bold;">${data.quadrant}</span><br/>
                      📝 特征: ${quadrantDesc}
                    </div>`
          }
        },
        legend: {
          data: ['明星产品', '问题产品', '现金牛产品', '瘦狗产品'],
          top: 30,
          itemGap: 20,
          formatter: name => {
            const icons = {
              '明星产品': '⭐',
              '问题产品': '❓',
              '现金牛产品': '🐄',
              '瘦狗产品': '🐕'
            }
            return `${icons[name] || ''} ${name}`
          }
        },
        grid: {
          left: '12%',
          right: '8%',
          bottom: '12%',
          top: '20%'
        },
        xAxis: {
          type: 'value',
          name: '库存周转率(%)',
          nameLocation: 'middle',
          nameGap: 30,
          splitLine: {
            show: true,
            lineStyle: {
              color: '#e0e0e0',
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '毛利率(%)',
          nameLocation: 'middle',
          nameGap: 40,
          splitLine: {
            show: true,
            lineStyle: {
              color: '#e0e0e0',
              type: 'dashed'
            }
          }
        },
        // 添加象限分割线
        graphic: [
          // 垂直分割线
          {
            type: 'line',
            shape: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: 1
            },
            style: {
              stroke: '#ff6b6b',
              lineWidth: 2,
              lineDash: [5, 5]
            },
            silent: true,
            z: 1
          },
          // 水平分割线
          {
            type: 'line',
            shape: {
              x1: 0,
              y1: 0,
              x2: 1,
              y2: 0
            },
            style: {
              stroke: '#ff6b6b',
              lineWidth: 2,
              lineDash: [5, 5]
            },
            silent: true,
            z: 1
          },
          // 象限标签
          {
            type: 'text',
            style: {
              text: '⭐ 明星产品\n高周转 + 高毛利',
              x: 0.75,
              y: 0.25,
              textAlign: 'center',
              textVerticalAlign: 'middle',
              fontSize: 12,
              fontWeight: 'bold',
              fill: '#4CAF50',
              backgroundColor: 'rgba(255,255,255,0.8)',
              padding: [5, 8],
              borderRadius: 4
            },
            silent: true,
            z: 2
          },
          {
            type: 'text',
            style: {
              text: '❓ 问题产品\n低周转 + 高毛利',
              x: 0.25,
              y: 0.25,
              textAlign: 'center',
              textVerticalAlign: 'middle',
              fontSize: 12,
              fontWeight: 'bold',
              fill: '#FF9800',
              backgroundColor: 'rgba(255,255,255,0.8)',
              padding: [5, 8],
              borderRadius: 4
            },
            silent: true,
            z: 2
          },
          {
            type: 'text',
            style: {
              text: '🐄 现金牛产品\n高周转 + 低毛利',
              x: 0.75,
              y: 0.75,
              textAlign: 'center',
              textVerticalAlign: 'middle',
              fontSize: 12,
              fontWeight: 'bold',
              fill: '#2196F3',
              backgroundColor: 'rgba(255,255,255,0.8)',
              padding: [5, 8],
              borderRadius: 4
            },
            silent: true,
            z: 2
          },
          {
            type: 'text',
            style: {
              text: '🐕 瘦狗产品\n低周转 + 低毛利',
              x: 0.25,
              y: 0.75,
              textAlign: 'center',
              textVerticalAlign: 'middle',
              fontSize: 12,
              fontWeight: 'bold',
              fill: '#9E9E9E',
              backgroundColor: 'rgba(255,255,255,0.8)',
              padding: [5, 8],
              borderRadius: 4
            },
            silent: true,
            z: 2
          }
        ],
        series: [
          {
            name: 'SKU',
            type: 'scatter',
            data: this.filteredMatrixData.map(item => ({
              name: item.name || '未知SKU',
              value: [
                parseFloat(item.turnoverRate) || 0,
                parseFloat(item.marginRate) || 0,
                parseFloat(item.sales_amount) || 0
              ],
              quadrant: item.quadrant || '未分类',
              itemStyle: {
                color: '#2196F3', // 统一使用蓝色
                borderColor: '#fff',
                borderWidth: 1
              }
            })),
            symbolSize: data => {
              // 添加严格的空值检查
              if (!data || !data.value || !Array.isArray(data.value) || data.value.length < 3) {
                return 10 // 默认大小
              }
              const salesAmount = parseFloat(data.value[2]) || 0
              return Math.sqrt(Math.max(salesAmount, 0)) / 50 + 10
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            }
          }
        ]
      }

      // 动态设置分割线位置
      this.matrixChart.setOption(option)
      
      // 在图表渲染完成后设置分割线的实际位置
      setTimeout(() => {
        const chartInstance = this.matrixChart
        if (chartInstance) {
          const xAxisPixel = chartInstance.convertToPixel('grid', [turnoverMedian, 0])
          const yAxisPixel = chartInstance.convertToPixel('grid', [0, marginMedian])
          
          if (xAxisPixel && yAxisPixel) {
            const gridRect = chartInstance.getModel().getComponent('grid', 0).coordinateSystem.getArea()
            
            // 更新分割线位置
            option.graphic[0].shape = {
              x1: xAxisPixel[0],
              y1: gridRect.y,
              x2: xAxisPixel[0],
              y2: gridRect.y + gridRect.height
            }
            
            option.graphic[1].shape = {
              x1: gridRect.x,
              y1: yAxisPixel[1],
              x2: gridRect.x + gridRect.width,
              y2: yAxisPixel[1]
            }
            
            // 更新象限标签位置
            const centerX = gridRect.x + gridRect.width / 2
            const centerY = gridRect.y + gridRect.height / 2
            
            option.graphic[2].style.x = (xAxisPixel[0] + gridRect.x + gridRect.width) / 2
            option.graphic[2].style.y = (gridRect.y + yAxisPixel[1]) / 2
            
            option.graphic[3].style.x = (gridRect.x + xAxisPixel[0]) / 2
            option.graphic[3].style.y = (gridRect.y + yAxisPixel[1]) / 2
            
            option.graphic[4].style.x = (xAxisPixel[0] + gridRect.x + gridRect.width) / 2
            option.graphic[4].style.y = (yAxisPixel[1] + gridRect.y + gridRect.height) / 2
            
            option.graphic[5].style.x = (gridRect.x + xAxisPixel[0]) / 2
            option.graphic[5].style.y = (yAxisPixel[1] + gridRect.y + gridRect.height) / 2
            
            chartInstance.setOption(option)
          }
        }
      }, 100)
    },

    // 获取日期参数和组织ID参数
    getDateParams() {
      // 获取当前用户的组织ID，确保为数字类型
      const orgId = this.$store.getters.orgId || (this.$store.getters.user && this.$store.getters.user.deptId)
      
      const params = {
        startDate: this.dateRange && this.dateRange[0] ? this.dateRange[0] : null,
        endDate: this.dateRange && this.dateRange[1] ? this.dateRange[1] : null
      }
      
      // 如果有orgId，添加到参数中
      if (orgId) {
        params.orgId = parseInt(orgId)
      }
      
      return params
    },

    // 日期变化处理
    handleDateChange() {
      this.loadAllData()
    },

    // 刷新数据
    refreshData() {
      this.loadAllData()
    },

    // 窗口大小变化处理
    handleResize() {
      if (this.trendChart) this.trendChart.resize()
      if (this.categoryChart) this.categoryChart.resize()
      if (this.matrixChart) this.matrixChart.resize()
    },

    // 获取象限颜色
    getQuadrantColor(quadrant) {
      const colors = {
        '明星产品': '#4CAF50',
        '问题产品': '#FF9800',
        '现金牛产品': '#2196F3',
        '瘦狗产品': '#9E9E9E'
      }
      return colors[quadrant] || '#909399'
    },

    // 获取象限描述
    getQuadrantDescription(quadrant) {
      const descriptions = {
        '明星产品': '高周转率、高毛利率，是企业的核心盈利产品',
        '问题产品': '低周转率、高毛利率，需要改善销售策略',
        '现金牛产品': '高周转率、低毛利率，提供稳定现金流',
        '瘦狗产品': '低周转率、低毛利率，考虑优化或淘汰'
      }
      return descriptions[quadrant] || '未分类产品'
    },

    // 计算中位数
    calculateMedian(arr) {
      if (!arr || arr.length === 0) return 0
      const sorted = [...arr].sort((a, b) => a - b)
      const mid = Math.floor(sorted.length / 2)
      return sorted.length % 2 === 0 
        ? (sorted[mid - 1] + sorted[mid]) / 2 
        : sorted[mid]
    },

    // 获取象限标签类型
    getQuadrantType(quadrant) {
      const types = {
        '明星产品': 'success',
        '潜力产品': 'primary',
        '引流产品': 'warning',
        '滞销产品': 'danger'
      }
      return types[quadrant] || 'info'
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return Number(num).toLocaleString()
    },

    // 格式化百分比
    formatPercent(num) {
      if (!num) return '0.00'
      return Number(num).toFixed(2)
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 过滤开关变化处理
    onFilterChange() {
      this.filterOutliers()
      this.renderMatrixChart()
    },

    // SKU筛选相关方法
    // 应用SKU筛选到数据
    applySkuFilterToData() {
      if (!this.selectedSkuIds || this.selectedSkuIds.length === 0) {
        // 如果没有选择SKU，显示所有数据
        this.matrixData = [...this.originalMatrixData]
      } else {
        // 根据选中的SKU ID筛选数据
        this.matrixData = this.originalMatrixData.filter(item => 
          this.selectedSkuIds.includes(item.sku_id)
        )
      }
    },

    // SKU筛选输入处理
    handleSkuFilter(selectedIds) {
      this.selectedSkuIds = selectedIds || []
    },

    // 应用SKU筛选
    applySkuFilter() {
      this.applySkuFilterToData()
      this.filterOutliers()
      this.renderMatrixChart()
      this.$message.success(`已筛选 ${this.matrixData.length} 条SKU数据`)
    },

    // 清除SKU筛选
    clearSkuFilter() {
      this.selectedSkuIds = []
      this.applySkuFilterToData()
      this.filterOutliers()
      this.renderMatrixChart()
      this.$message.success('已清除SKU筛选条件')
    },

    // SKU API方法
    listSku,
    getSku
  }
}
</script>

<style scoped>
.page-title {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.stat-icon {
  font-size: 40px;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-title i {
  margin-right: 8px;
  color: #409EFF;
}

.chart-container {
  width: 100%;
}

.mb20 {
  margin-bottom: 20px;
}

.mt20 {
  margin-top: 20px;
}

.mr10 {
  margin-right: 10px;
}

.text-right {
  text-align: right;
}
</style>